package com.team.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;

import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;
import com.team.dao.UserDao;
import com.team.entity.User;
import com.team.util.Const;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String captcha = request.getParameter("captcha");
		System.out.println(captcha);
		if(SimpleImageCaptchaServlet.validateResponse(request, captcha)){
			//succ
			String name = request.getParameter("username");
			String pwd = request.getParameter("password");
			if(name==null||pwd==null){
				response.sendRedirect("index.jsp?code=1002");
				return ;
			}
			//pwd += "2012kaishengitpms";
			
			//pwd = DigestUtils.md5Hex(pwd);
			UserDao ud = new UserDao();
			/*User user=ud.selectByNameAndPwd(name, pwd);
			if(user == null){
				response.sendRedirect("index.jsp?code=1004");
				return ;
				
			}else {
				response.sendRedirect("listProj.jsp");
				return ;
			}*/
			List<User> list = ud.selectListByName(name);
			if(list == null){
				response.sendRedirect("index.jsp?code=1003");
				return ;
			}else {
				for(User user:list){
					if( user.getPassword().equals(pwd)){
						HttpSession session = request.getSession();
						session.setAttribute(Const.SESSION_USER, user);
						response.sendRedirect("newProj.jspx?_m=select");
					}else {
						response.sendRedirect("index.jsp?code=1004");
						return ;
					}
					
				}
			}
		}else {
			response.sendRedirect("index.jsp?code=1001");
			return;
			//error
		}
	}

}
